<template>
    <div class="category-container">

        <div class="top-bar">
            <div class="search-area">
                <label>计量单位:</label>
                <el-input v-model="searchKeyword" placeholder="输入计量单位名称" style="width: 200px; margin-right: 10px;" />
                <el-button type="primary" @click="handleSearch">查询</el-button>
            </div>
        </div>

        <!-- 单计量单位 -->
        <div>
            <div class="action-buttons">
                <label>单计量单位</label>
                <el-button type="primary" @click="openAddSingleUnitDialog">新增</el-button>
            </div>
            <el-table :data="singleUnitList" border style="width: 100%" stripe v-loading="singletableLoad" height="200">
                <el-table-column prop="operation" label="操作" width="100">
                    <template #default="{ row }">
                        <el-button size="small" @click="editSingleUnit(row.id)">
                            <el-icon>
                                <Edit />
                            </el-icon>
                        </el-button>
                        <el-button size="small" @click="deleteSingleUnit(row.id)">
                            <el-icon>
                                <Delete />
                            </el-icon>
                        </el-button>
                    </template>
                </el-table-column>

                <el-table-column prop="name" label="名称" width="300">
                    <template #default="{ row }">
                        {{ row.name }}
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <br />

        <!-- 多计量单位 -->
        <div>
            <div class="action-buttons">
                <label>多计量单位</label>
                <el-button type="primary" @click="openAddMultipleUnitDialog">新增</el-button>
            </div>
            <el-table :data="multipleUnitList" border style="width: 100%" v-loading="multipleUnitLoad" height="200"
                stripe>
                <el-table-column prop="operation" label="操作" width="100">
                    <template #default="{ row }">
                        <el-button size="small" @click="editMultipleUnitDialog(row.id)">
                            <el-icon>
                                <Edit />
                            </el-icon>
                        </el-button>
                        <el-button size="small" @click="deleteMultipleUnit(row.id)">
                            <el-icon>
                                <Delete />
                            </el-icon>
                        </el-button>
                    </template>
                </el-table-column>

                <el-table-column prop="name" label="名称" width="300">
                    <template #default="{ row }">
                        {{ row.name }}
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 新增/编辑 单计量单位弹窗 -->
        <el-dialog v-model="singleUnitDialogVisible" :title="dialogSingleUnitType ? '编辑单计量单位' : '新增单计量单位'" width="400px"
            @close="resetSingleForm">
            <div class="dialog-form">
                <div class="form-item">
                    <label class="label">名称:</label>
                    <el-input v-model="singleUnitForm.name" placeholder="请输入单位名称" />
                </div>
            </div>

            <template #footer>
                <el-button @click="singleUnitDialogVisible = false">关闭</el-button>
                <el-button type="primary" @click="saveSingleUnit" :loading="singleSaving">
                    {{ dialogSingleUnitType ? '更新' : '保存' }}
                </el-button>
            </template>
        </el-dialog>

        <!-- 新增/编辑 多计量单位弹窗 -->
        <el-dialog v-model="multipleUnitDialogVisible" :title="dialogMultipleUnitType ? '编辑多计量单位' : '新增多计量单位'"
            width="500px" @close="resetForm">
            <el-form :model="multipleUnitForm" label-width="100px" :rules="rules" ref="form2">
                <el-form-item label="多单位名称">
                    <el-input :value="createName" readonly style="background: #f0f0f0;"></el-input>
                </el-form-item>
                <el-form-item label="基本单位" prop="basicUnit">
                    <el-input v-model="multipleUnitForm.basicUnit" maxlength="5" placeholder="如：瓶" />
                </el-form-item>

                <!-- 动态生成的副单位 -->
                <el-form-item v-for="(unit, index) in multipleUnitForm.deputyUnit" :key="index"
                    :label="`副单位${index + 1}`">
                    <el-input style="width: 130px;" v-model="unit.name" placeholder="单位名称" />

                    <span class="left" style="margin: 0 5px;">=</span>

                    <el-input-number v-model="unit.conversion" :step="1" controls-position="right" style="width: 110px;"
                        placeholder="换算比例" @change="(val) => changeConversion(val, unit)" />

                    <span class="left">{{ multipleUnitForm.basicUnit }}</span>

                    <el-button link type="danger" class="left delete-btn" @click="removeDeputyUnit(index)">
                        <el-icon>
                            <Delete />
                        </el-icon>
                    </el-button>
                </el-form-item>

                <el-form-item>
                    <el-button @click="addDeputyUnit">
                        增加单位
                    </el-button>
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button type="primary" @click="saveMultipleUnits" :loading="multipleSaving">
                    {{ dialogMultipleUnitType ? '更新' : '保存' }}
                </el-button>
                <el-button @click="multipleUnitDialogVisible = false">关闭</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const searchKeyword = ref('')

const singleSaving = ref(false)
const multipleSaving = ref(false)


const singletableLoad = ref(false)
const multipleUnitLoad = ref(false)

// 单计量单位弹窗
const singleUnitDialogVisible = ref(false)
const dialogSingleUnitType = ref(false)

// 单计量单位表单
const singleUnitForm = ref({ name: '' })

// 多计量单位弹窗
const multipleUnitDialogVisible = ref(false)
const dialogMultipleUnitType = ref(false)

// 多计量单位表单
const multipleUnitForm = ref({
    id: null,
    name: '',
    basicUnit: '',
    deputyUnit: [{
        name: '',
        conversion: null,
    }]
})

// 单计量单位列表
const singleUnitList = ref([])


// 搜索
const handleSearch = () => {
    getSingleUnitList()
    getMultipleUnitList()

}

const getSingleUnitList = async () => {
    singletableLoad.value = true
    try {
        const res = await axios.get('/api/basic/goods/allSingleUnit', { params: { name: searchKeyword.value.trim() } })

        if (res.data.code === 5200) {
            singleUnitList.value = res.data.singleUnitList
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    } finally {
        singletableLoad.value = false
    }
}

// 打开新增弹窗
const openAddSingleUnitDialog = () => {
    dialogSingleUnitType.value = false
    singleUnitForm.value.name = ''
    singleUnitDialogVisible.value = true
}

// 编辑单单位
const editSingleUnit = async (id) => {
    dialogSingleUnitType.value = true

    try {
        const res = await axios.get('/api/basic/goods/singleUnitById', { params: { id } })
        if (res.data.code === 5200) {
            singleUnitForm.value = res.data.singleUnit
            singleUnitDialogVisible.value = true
        } else {
            ElMessage.error('获取数据失败')
        }
    } catch (error) {
        ElMessage.error(error.message)
    }
}

// 保存单计量单位
const saveSingleUnit = async () => {

    try {

        singleSaving.value = true
        if (!singleUnitForm.value.name.trim()) {
            ElMessage.error('请输入单位名称')
            return
        }


        const url = dialogSingleUnitType.value ? '/api/basic/goods/updateSingleUnit' : '/api/basic/goods/addSingleUnit'
        const res = await axios.post(url, singleUnitForm.value)
        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            singleUnitDialogVisible.value = false
            await getSingleUnitList()
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    } finally {
        singleSaving.value = false
    }
}

// 删除
const deleteSingleUnit = async (id) => {

    try {
        await ElMessageBox.confirm('此操作将永久删除该单位, 是否继续?', '删除单位', { type: 'warning' })
    } catch {
        return ElMessage.info('取消删除')
    }

    try {
        const res = await axios.post('/api/basic/goods/deleteSingleUnit', null, { params: { id } })
        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            await getSingleUnitList()
        }
    } catch (error) {
        ElMessage.error(error.message)
    }
}

// 多计量单位列表
const multipleUnitList = ref([])

const getMultipleUnitList = async () => {
    multipleUnitLoad.value = true
    try {
        const res = await axios.get('/api/basic/goods/allMultipleUnit', { params: { name: searchKeyword.value.trim() } })

        if (res.data.code === 5200) {
            multipleUnitList.value = res.data.multipleUnitList
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    } finally {
        multipleUnitLoad.value = false
    }
}

const changeConversion = (val, unit) => {
    if (val != null && val <= 1) {
        ElMessage.warning('副单位换算比例必须大于1')
        unit.conversion = null
    }
}

// 打开新增多单位弹窗
const openAddMultipleUnitDialog = () => {
    dialogMultipleUnitType.value = false
    multipleUnitForm.value = {
        id: null,
        name: '',
        basicUnit: '',
        deputyUnit: [{ name: '', conversion: null }]
    }
    multipleUnitDialogVisible.value = true
}

// 编辑多单位
const editMultipleUnitDialog = async (id) => {
    dialogMultipleUnitType.value = true

    try {
        const res = await axios.get('/api/basic/goods/multipleUnitById', { params: { id } })
        if (res.data.code === 5200) {
            const multipleUnit = res.data.multipleUnit
            const basicUnit = multipleUnit.unitsDetailsList.find(unit => unit.conversion === 1)
            const deputyUnit = multipleUnit.unitsDetailsList.filter(unit => unit.conversion !== 1)
            multipleUnitForm.value.id = multipleUnit.id
            multipleUnitForm.value.basicUnit = basicUnit.name
            multipleUnitForm.value.deputyUnit = deputyUnit
            multipleUnitDialogVisible.value = true
        } else {
            ElMessage.error('获取多单位详情失败')
        }
    } catch (error) {
        ElMessage.error(error.message)
    }
}

// 自动生成多单位名称
const createName = computed(() => {
    const { basicUnit, deputyUnit } = multipleUnitForm.value
    if (!basicUnit.trim()) return ''

    // 过滤出 name 非空、conversion > 0 的副单位
    const validDeputy = deputyUnit.filter(
        unit => unit.name?.trim() && unit.conversion > 0
    )

    const unitNames = [basicUnit.trim(), ...validDeputy.map(u => u.name.trim())]


    const ratios = [1, ...validDeputy.map(u => u.conversion)]

    let result = unitNames.join(',')
    if (validDeputy.length > 0) {
        result += `(${ratios.join(':')})`
    }
    return result
})

// 增加副单位
const addDeputyUnit = () => {
    multipleUnitForm.value.deputyUnit.push({ name: '', conversion: '' })
}

// 删除副单位
const removeDeputyUnit = (index) => {
    if (multipleUnitForm.value.deputyUnit.length <= 1) {
        ElMessage.warning('至少需要保留一个副单位')
        return
    }

    multipleUnitForm.value.deputyUnit.splice(index, 1)
}

// 重置多单位表单
const resetForm = () => {
    multipleUnitForm.value = {
        id: null,
        name: '',
        basicUnit: '',
        deputyUnit: [{ name: '', conversion: '' }]
    }
}

// 保存多计量单位（新增或更新）
const saveMultipleUnits = async () => {

    try {

        multipleSaving.value = true
        if (!multipleUnitForm.value.basicUnit.trim()) {
            ElMessage.error('请填写基本单位')
            return
        }

        if (!multipleUnitForm.value.deputyUnit.length) {
            ElMessage.error('请填写至少一个副单位')
            return
        }

        // 校验副单位：至少有一个有效副单位（name 和 conversion 都有）
        const validDeputy = multipleUnitForm.value.deputyUnit.filter(
            unit => unit.name?.trim() && unit.conversion > 0
        )

        if (validDeputy.length === 0) {
            ElMessage.error('请至少添加一个有效的副单位（单位名称和换算比例）')
            return
        }


        // 构建请求数据
        const requestData = {
            id: multipleUnitForm.value.id,
            name: createName.value.trim(),
            basicUnit: multipleUnitForm.value.basicUnit.trim(),
            deputyUnitList: validDeputy.map(unit => ({
                name: unit.name.trim(),
                conversion: unit.conversion
            }))
        }

        const url = dialogMultipleUnitType.value ? '/api/basic/goods/updateMultipleUnit' : '/api/basic/goods/addMultipleUnit'

        const res = await axios.post(url, requestData)

        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            multipleUnitDialogVisible.value = false
            await getMultipleUnitList() // 刷新列表
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    } finally {
        multipleSaving.value = false
    }
}

// 删除多计量单位
const deleteMultipleUnit = async (id) => {
    try {
        await ElMessageBox.confirm('此操作将永久删除该多计量单位，是否继续？', '提示',)
    } catch {
        return ElMessage.info('已取消删除')
    }

    try {
        const res = await axios.post('/api/basic/goods/deleteMultipleUnit', null, {
            params: { id }
        })

        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg || '删除成功')
            await getMultipleUnitList() // 刷新列表
        } else {
            ElMessage.error(res.data.msg || '删除失败')
        }
    } catch (error) {
        ElMessage.error(error.message || '网络错误，请稍后重试')
    }
}

onMounted(() => {
    getSingleUnitList()
    getMultipleUnitList()
})
</script>

<style scoped>
.category-container {
    padding: 20px;
    background-color: #fff;
}

.top-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.search-area {
    display: flex;
    align-items: center;
    gap: 10px;
}

.action-buttons {
    display: flex;
    gap: 10px;
    align-items: center;
}

.el-table {
    margin-top: 10px;
}

.el-table .el-table__row:nth-child(even) {
    background-color: #f5f7fa;
}

.el-button--small {
    padding: 5px 8px;
    font-size: 12px;
}

.dialog-form {
    padding: 20px;
    font-size: 14px;
}

.form-item {
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.label {
    width: 100px;
    text-align: right;
    color: #333;
}

.el-input,
.el-input-number {
    flex: 1;
    max-width: 150px;
}

.el-button--text {
    font-size: 12px;
    padding: 0;
}

/* 只读输入框 */
.el-input.is-disabled /deep/ .el-input__inner {
    background-color: #f5f7fa;
    color: #666;
    cursor: not-allowed;
}
</style>